<template>
  <div class="gesture-attendance">
    <div class="page-header">
      <i class="el-icon-edit"></i>
      创建手势签到
      <div class="header-desc">设置签到手势和有效时间，学生需要正确绘制手势图案完成签到</div>
    </div>
    <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="attendance-form">
      <el-form-item label="签到标题" prop="title" required>
        <el-input
          v-model="form.title"
          placeholder="请输入签到标题，如：第1节课签到">
        </el-input>
      </el-form-item>
      <el-form-item label="选择班级" prop="classroomId" required>
        <el-select
          v-model="form.classroomId"
          placeholder="请选择班级"
          style="width: 100%">
          <el-option
            v-for="item in classrooms"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="签到手势" prop="gestureSequence" required>
        <div class="gesture-container">
          <canvas
            ref="gestureCanvas"
            class="gesture-canvas"
            width="300"
            height="300">
          </canvas>
          <div class="gesture-points">
            <div class="gesture-row" v-for="row in 3" :key="row">
              <div
                v-for="col in 3"
                :key="col"
                class="gesture-point"
                :class="{ 'active': isPointActive((row-1)*3 + col) }"
                @click="selectPoint((row-1)*3 + col)">
                {{ (row-1)*3 + col }}
              </div>
            </div>
          </div>
        </div>
        <div class="gesture-tip">
          <div class="direction-tips">
            请按顺序点击数字，将自动连线
          </div>
          <el-button type="text" @click="clearGesture">清除手势</el-button>
        </div>
        <div class="selected-sequence" v-if="form.gestureSequence">
          已选择的点序列：{{ form.gestureSequence }}
        </div>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" required>
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 220px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime" required>
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 220px">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          :disabled="!form.gestureSequence"
          class="submit-btn">
          创建签到
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'GestureAttendance',
  data() {
    return {
      form: {
        title: '',
        classroomId: '',
        gestureSequence: '',
        startTime: '',
        endTime: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入签到标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        classroomId: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        gestureSequence: [
          { required: true, message: '请绘制签到手势', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      },
      classrooms: [],
      loading: false,
      currentSequence: [],
      activePoints: new Set(),
      points: [],
      ctx: null
    }
  },
  mounted() {
    this.initCanvas()
    this.getClassrooms()
  },
  methods: {
    initCanvas() {
      const canvas = this.$refs.gestureCanvas
      this.ctx = canvas.getContext('2d')
      this.ctx.strokeStyle = '#409EFF'
      this.ctx.lineWidth = 3
      this.ctx.lineCap = 'round'
      this.ctx.lineJoin = 'round'
      this.ctx.shadowColor = '#409EFF'
      this.ctx.shadowBlur = 5

      // 初始化9个点的位置
      const padding = 40
      const spacing = (canvas.width - 2 * padding) / 2
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          this.points.push({
            x: padding + col * spacing,
            y: padding + row * spacing,
            point: row * 3 + col + 1
          })
        }
      }
    },
    drawLines() {
      // 清除画布
      this.ctx.clearRect(0, 0, this.$refs.gestureCanvas.width, this.$refs.gestureCanvas.height)

      if (this.currentSequence.length > 0) {
        this.ctx.beginPath()
        const firstPoint = this.points.find(p => p.point === this.currentSequence[0])
        this.ctx.moveTo(firstPoint.x, firstPoint.y)

        for (let i = 1; i < this.currentSequence.length; i++) {
          const point = this.points.find(p => p.point === this.currentSequence[i])
          this.ctx.lineTo(point.x, point.y)
        }

        this.ctx.stroke()
      }
    },
    canSelectPoint(point) {
      if (this.currentSequence.length === 0) return true

      const lastPoint = this.currentSequence[this.currentSequence.length - 1]
      const lastPointIndex = lastPoint - 1
      const currentPointIndex = point - 1

      // 计算两个点之间的曼哈顿距离
      const lastRow = Math.floor(lastPointIndex / 3)
      const lastCol = lastPointIndex % 3
      const currentRow = Math.floor(currentPointIndex / 3)
      const currentCol = currentPointIndex % 3

      const rowDiff = Math.abs(lastRow - currentRow)
      const colDiff = Math.abs(lastCol - currentCol)

      // 如果两个点相邻（包括对角线），则允许选择
      return rowDiff <= 1 && colDiff <= 1
    },
    selectPoint(point) {
      if (!this.activePoints.has(point) && this.canSelectPoint(point)) {
        this.currentSequence.push(point)
        this.activePoints.add(point)
        this.form.gestureSequence = this.currentSequence.join('')
        this.drawLines()
      }
    },
    async getClassrooms() {
      try {
        const res = await this.$http.get('/api/teacher/classroom/list')
        this.classrooms = res.data.records
      } catch (error) {
        this.$message.error('获取班级列表失败')
      }
    },
    clearGesture() {
      this.form.gestureSequence = ''
      this.currentSequence = []
      this.activePoints.clear()
      this.ctx.clearRect(0, 0, this.$refs.gestureCanvas.width, this.$refs.gestureCanvas.height)
    },
    isPointActive(point) {
      return this.activePoints.has(point)
    },
    async handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true
          let res
          try {
            res = await this.$http.post('/api/teacher/attendance/gesture', this.form)
            if (res.code === 1) {
              this.$message.success('手势签到创建成功')
              // 不清除表单，保持当前状态
              this.loading = false
            } else {
              this.$message.error(res.msg)
              this.loading = false
            }
          } catch (error) {
            if (error.response && error.response.data) {
              this.$message.error(error.response.data.msg)
            } else {
              this.$message.error('创建手势签到失败')
            }
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.gesture-attendance {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.page-header i {
  margin-right: 8px;
  color: #409EFF;
}

.header-desc {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
  margin-left: 20px;
}

.attendance-form {
  max-width: 800px;
}

.gesture-container {
  position: relative;
  width: 300px;
  height: 300px;
}

.gesture-canvas {
  position: absolute;
  top: 0;
  left: 0;
  background: #f5f7fa;
  border-radius: 8px;
  z-index: 1;
}

.gesture-points {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 40px;
  box-sizing: border-box;
  z-index: 2;
}

.gesture-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 70px;
}

.gesture-row:last-child {
  margin-bottom: 0;
}

.gesture-point {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
  transition: all 0.3s;
  background: #fff;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.gesture-point:hover {
  border-color: #409EFF;
  color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.gesture-point.active {
  border-color: #409EFF;
  background-color: #ecf5ff;
  color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
}

.gesture-tip {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.direction-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.6;
}

.selected-sequence {
  margin-top: 10px;
  color: #409EFF;
  font-size: 14px;
}

.submit-btn {
  width: 200px;
}
</style>

